#include "kit/event/StatusUpdateEvent.hpp"
#include <string>
#include <vector>


namespace KitEvent
{

	StatusUpdateEvent::~StatusUpdateEvent()
	{

	}
	void StatusUpdateEvent::execute(KitUser::UserMap * iUsers)
	{
		// check if the user that changed status exists
		if(this->isValid(iUsers))
		{
			KitUser::User * aFrom = iUsers->get(_message->getFrom());
			// then for every of his followers
			std::vector<std::string> aFollowers = aFrom->getFollowers();
			for(int i = 0; i < aFollowers.size(); ++i)
			{
				std::string aCurFollower = aFollowers[i];
				// if the follower is present, send him a message
				if(iUsers->contains(aCurFollower))
				{

					try
					{
						iUsers->get(aCurFollower)->getConnection()->write(_message->getPayload());
					}
					catch(SystemSocket::WriteException & aException)
					{
						// if we couldn't write anymore on the connection mark it as invalid
						iUsers->get(aCurFollower)->getConnection()->markInvalid();
					}
				}
			}
		}
	}

	bool StatusUpdateEvent::isValid(KitUser::UserMap * iUsers)
	{
		return iUsers->contains(_message->getFrom());
	}
}
